package com.itheima.health.mobile.controller;

import com.itheima.health.BusinessException;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.ServletException;

/**
 * @Author: 位帅帅
 * @Date: 15:18 2021/1/10
 * @Description: 统一异常处理
 */
@RestControllerAdvice()
@Slf4j
public class MyExceptionHandle {
    /**
     * @Author: 位帅帅
     * @Date: 15:21 2021/1/10
     * @Params: [e]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 服务端异常, 提示操作失败
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({Exception.class})
    public Result exception(Exception e) {
        log.error("e: {}", e.getMessage());
        return new Result(false, MessageConst.ACTION_FAIL);
    }

    /**
     * @Author: 位帅帅
     * @Date: 15:23 2021/1/10
     * @Params: [e]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 业务异常:自定义
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({BusinessException.class})
    public Result businessRuntimeException(Exception e) {
        log.error("e: {}", e.getMessage());
        return new Result(false, e.getMessage());
    }

    /**
     * @Author: 位帅帅
     * @Date: 15:26 2021/1/10
     * @Params: [e]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 交给spring处理的异常, 继续上抛
     */
    @ExceptionHandler({
            ServletException.class,//mediaType不匹配,method不匹配
            HttpMessageConversionException.class,//http body转换异常,@requestBody的参数
            MethodArgumentNotValidException.class,//http请求缺少查询参数
            MethodArgumentTypeMismatchException.class})//http请求参数类型不匹配
    public Result servletException(Exception e) throws Exception {
        throw e;
    }
}
